/**
 * 使用api
 */
export function useToolApi() {
  let lodash = ZY.lodash;

  function travel(o = {}, {obj ={ }, path = [],  keys = [], handle = {}} = {}) {
    if (o.type === 'object') {
      lodash.each(o.properties, function (item, key) {
        travel(item, {
          obj,
          path: path.concat(['properties', key]),
          keys,
          handle
        })
      })
    }
    else if (o.type === 'array') {

    }
    else {
      let s_path = ZY.getObjPathFromPathArr(path);
      let pickedProp = lodash.pick(o, keys);
      // console.log(s_path, o, keys, pickedProp, handle)
      if (handle && handle.beforeSet) {
        handle.beforeSet(pickedProp)
      }
      lodash.set(obj, s_path, pickedProp)
    }
  }

  function purfyObj(o = {}, keys = [], handle = {}) {
    let obj = {}
    let path = []
    travel(o, {obj, path, keys, handle});
    return obj;
  }

  /**
   * saveJson 创建表
   * @param serverProps {string}
   * @param fileName {string}
   * @param newProps {{}}
   * @param oldProps {{}}
   * @param tableName {string}
   * @param headers {{}}
   * @param data {{}}
   * @returns {Promise<*>}
   */
  async function saveJson(serverProps = '', fileName = '',
                          {headers = {}, newProps = {}, oldProps = {}, tableName = '',  data = {}} = {} ) {

    const PICKED_PROPS = ['type', 'sub_type', 'rules', 'no_field']
    let _oldProps = {}
    if (typeof oldProps === 'string') {
      try {
        _oldProps = ZY.JSON5.parse(oldProps)
      } catch (e) {
        _oldProps = {}
      }
    } else {
      _oldProps = oldProps
    }

    let purfyHandle = {
      beforeSet(obj) {
        // console.log('beforeSet', obj)
      }
    }
    let oldPur = purfyObj(_oldProps, PICKED_PROPS, purfyHandle);
    let newPur = purfyObj(newProps, PICKED_PROPS, purfyHandle);
    let detailedDiff = {
      "added": {},
      "deleted": {},
      "updated": {}
    }
    // console.log(_oldProps, newProps)
    if (Object.keys(_oldProps).length > 0) {
       detailedDiff = ZY.detailedDiff(oldPur, newPur);
    }
    // console.log(detailedDiff)
    try {
      // 这次的文件
      let file = new File([serverProps], fileName, {
        type: "text/plain",
      });
      // 和上次的差别
      let diffed = new File([ZY.JSON5.stringify(detailedDiff)], fileName, {
        type: "text/plain",
      });
      let oldPropFile = new File([_oldProps], fileName, {
        type: "text/plain",
      });
      // console.log(serverProps)
      let formdata = new FormData();
      // formdata.append('tableName', tableName)
      formdata.append('file', file);
      formdata.append('diffed', diffed);
      formdata.append('oldProps', oldPropFile);
      if (data) {
        Object.entries(data).forEach(([key, item]) => {
          formdata.append(key, item);
        })
      }
      // downloadFiles('testdata', new Map([
      //   ['file.json5', file],
      //   ['diffed.json5', diffed],
      //   ['oldProps.json5', oldPropFile]
      // ]))
      let res = await Req.post('/api/zy-boot/json/json5', formdata, {
        headers: {

          'Content-Type': 'multipart/form-data;charset=UTF-8',
          ...headers
        }
      })

      return res.result;
    } catch (e) {
      console.log('saveJson err', e)
      return Promise.reject(e)
    }
  }

  return {saveJson}
}

/**
 * 获取缓存的文件
 * @param params {{}}
 * @returns {Promise<any>}
 */
export async function reqCacheFile(params = {}) {
  let [err, res] = await ZY.awaitTo(globalThis.Req.get('/api/zy-boot/json/getVueFile', {
    params
  }));
  if (err) {
    console.log('get file failed', err)
    return Promise.reject(err);
  }
  if (res.result) {
    let url = res?.result?.url
    let [fetchErr, fetchRes] = await ZY.awaitTo(fetch(url));
    if (fetchErr) {
      console.log('fetch file failed', fetchErr)
      return Promise.reject(fetchErr);
    }
    return fetchRes.text();
  }
  return res.result
}

/**
 * 获取库中所有表名
 * @param params
 * @returns {Promise<*>}
 */
export async function reqTables( params = {}) {
  let [err, res] = await ZY.awaitTo(globalThis.Req.get('/api/zy-boot/json/getTableSchemaList', {
    params: {
      ...params
    }
  }));
  if (err) {
    console.log('get file failed', err)
    return Promise.reject(err);
  }
  if (res.result) {
    return res.result
  }
}

/**
 * 获取表名获取结构
 * @param tableName
 * @param params
 * @returns {Promise<*>}
 */
export async function reqTableParam(tableName, params = {}) {
  let [err, res] = await ZY.awaitTo(globalThis.Req.get('/api/zy-boot/json/getTableParam', {
    params: {
      tableName,
      ...params
    }
  }));
  if (err) {
    console.log('get file failed', err)
    return Promise.reject(err);
  }
  if (res.result) {
    return res.result
  }
}

/**
 * 保存表关联记录
 * @param recordList {[{}]}
 * @param data
 * @param options
 * @returns {Promise<*>}
 */
export async function saveTableRecord(recordList = [], data = {}, options) {
  let [err, res] = await ZY.awaitTo(globalThis.Req.post('/api/zy-boot/json/saveTableRecord',recordList, options));
  if (err) {
    console.log('get file failed', err)
    return Promise.reject(err);
  }
  if (res) {
    globalThis.ElMessage.success('保存成功');
    return res
  }
}


/**
 * 保存表关联记录
 * @param recordList {[{}]}
 * @param data
 * @param options
 * @returns {Promise<*>}
 */
export async function saveTableRecordFile(recordList = [], data = {}, options) {
  let [err, res] = await ZY.awaitTo(globalThis.Req.post('/api/zy-boot/json/saveTableRecord',recordList, options));
  if (err) {
    console.log('get file failed', err)
    return Promise.reject(err);
  }
  if (res) {
    globalThis.ElMessage.success('保存成功');
    return res
  }
}

/**
 *
 * @param params
 * @param options
 * @returns {Promise<*>}
 */
export async function getInterfaceList(params = {}, options = {}) {
  let [err, res] = await ZY.awaitTo(globalThis.Req.post('/api/zy-boot/dataSource/getInterfaceList', {
    params: {
      ...params
    },
    ...options
  }));
  if (err) {
    console.log('get file failed', err)
    return Promise.reject(err);
  }
  if (res.result) {
    return res.result
  }
}
